package org.txazo.blog.commons.parse.base;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.txazo.blog.commons.io.StringLineReader;
import org.txazo.blog.commons.io.StringLineWriter;
import org.txazo.blog.commons.io.base.Writer;

public class CoreParser {

	private Writer writer = null;
	/** 写入标识 */
	private boolean writerFlag = false;
	/** 解析标识 */
	private boolean parserFlag = false;
	/** 代码段类型 */
	private String codeType = null;

	public void parseFile(String file) {
		try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream("D:/out.txt")));
				BufferedReader br = new BufferedReader(new InputStreamReader(
						new FileInputStream(file), "utf-8"))) {
			String temp = null;
			String trim = null;
			while ((temp = br.readLine()) != null) {
				trim = temp.trim();
				if (trim.startsWith(ParserUtil.TAG_PREFIX)
						&& ParserUtil.TAG_CODES.contains(trim)) {
					writerFlag = true;
					writer = new StringLineWriter();
					codeType = ParserUtil.getCodeType(trim);
					System.out.println("CodeType: " + codeType);
				} else if (trim.equals(ParserUtil.TAG_SUEFIX)) {
					writerFlag = false;
					parserFlag = true;
				} else if (writerFlag) {
					writer.write(temp);
				} else {
					bw.write(temp);
					bw.newLine();
				}

				if (parserFlag) {
					Parser parser = ParserFactory.getParser(codeType,
							new StringLineReader(writer));
					parser.parse(bw);
					parser.close();
					parserFlag = false;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new CoreParser()
				.parseFile("F:/GraduationProject/txazo/BlogSite/src/java/org/txazo/core/commons/parse/base/model.txt");
	}

}
